<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">






  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.png?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.png?v=5.1.4" color="#222">





  <meta name="keywords" content="Linux,正则表达式," />





  <link rel="alternate" href="/atom.xml" title="平步青云win" type="application/atom+xml" />






<meta name="description" content="介绍grep，sed，awk这三个命令，而正则表达式作为这三个命令的一种使用方式（命令输出中可以包含正则表达式）。">
<meta name="keywords" content="Linux,正则表达式">
<meta property="og:type" content="article">
<meta property="og:title" content="正则表达式基础">
<meta property="og:url" content="https://zxpgo.github.io/2018/09/01/正则表达式基础/index.html">
<meta property="og:site_name" content="平步青云win">
<meta property="og:description" content="介绍grep，sed，awk这三个命令，而正则表达式作为这三个命令的一种使用方式（命令输出中可以包含正则表达式）。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://i.imgur.com/lxmDrMs.png">
<meta property="og:image" content="https://i.imgur.com/0yauqRa.png">
<meta property="og:image" content="https://i.imgur.com/AFrutHC.png">
<meta property="og:image" content="https://i.imgur.com/XPbf0jn.png">
<meta property="og:image" content="https://i.imgur.com/i3jDsyH.png">
<meta property="og:image" content="https://i.imgur.com/oqIBw5Z.png">
<meta property="og:image" content="https://i.imgur.com/rsEeFmm.png">
<meta property="og:image" content="https://i.imgur.com/wp4CVrc.png">
<meta property="og:image" content="https://i.imgur.com/BQNSaoo.png">
<meta property="og:image" content="https://i.imgur.com/sBRTNbn.png">
<meta property="og:image" content="https://i.imgur.com/3DVhZlj.png">
<meta property="og:image" content="https://i.imgur.com/ZwgDOrO.png">
<meta property="og:image" content="https://i.imgur.com/crQqo4i.png">
<meta property="og:image" content="https://i.imgur.com/sdHzSiw.png">
<meta property="og:updated_time" content="2018-09-02T08:33:18.304Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="正则表达式基础">
<meta name="twitter:description" content="介绍grep，sed，awk这三个命令，而正则表达式作为这三个命令的一种使用方式（命令输出中可以包含正则表达式）。">
<meta name="twitter:image" content="https://i.imgur.com/lxmDrMs.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":10,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'PAO8LM7QB1',
      apiKey: '',
      indexName: 'Blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zxpgo.github.io/2018/09/01/正则表达式基础/"/>





  <title>正则表达式基础 | 平步青云win</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?7a4517a3ce6d7c50203655d056f01ac3";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">平步青云win</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-随笔">
          <a href="/sui" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            随笔
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
			
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zxpgo.github.io/2018/09/01/正则表达式基础/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zxp">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="平步青云win">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">正则表达式基础</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-01T15:57:50+08:00">
                2018-09-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/实验楼学习笔记之Linux/" itemprop="url" rel="index">
                    <span itemprop="name">实验楼学习笔记之Linux</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/09/01/正则表达式基础/" class="leancloud_visitors" data-flag-title="正则表达式基础">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p>介绍grep，sed，awk这三个命令，而正则表达式作为这三个命令的一种使用方式（命令输出中可以包含正则表达式）。<a id="more"></a></p>
<h2 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h2><p>正则表达式，又被正规表示式、正规表示法、针对表达式、规格表达式、常规表达法（Regular Expression,或regex、regexp、RE）。正则表达式使用单个字符来描述、匹配一系列符合某个句法规则的字符串。在很多编辑器里，正则表达式通常用来检索、替换那些符合某个模式的文本。</p>
<p>注意区分正则表达式与通配符的差别。</p>
<ul>
<li>在文本过滤工具里，都是用正则表达式，比如像awk，sed，等，是针对文件的内容的</li>
<li>而通配符多用在文件名上，比如查找find，ls，cp，等等</li>
</ul>
<p>具体内容对比，可以参考：<a href="https://blog.csdn.net/zgqxiexie/article/details/51184602" target="_blank" rel="noopener">https://blog.csdn.net/zgqxiexie/article/details/51184602</a></p>
<p>例子：</p>
<p>一个文件中，包含“shiyanlou”和“shilouyan”这两个字符，同样一个表达式：</p>
<pre><code>shi*
</code></pre><p>如果上述表达式作为正则表达式，它将只能匹配shi；而如果不是正则表达式，而是作为一个通配符，则将同时匹配两个字符串。</p>
<p>原因：在正则表达式中，<code>*</code>表示匹配前面的子表达式零次或多次，比如它可以匹配”sh”,”shi”,”shii”,”shishi”等等，而作为通配符<code>*</code>表示匹配通配符后面任意多个字符，所以可以匹配文本中的字符串。</p>
<h2 id="基本语法"><a href="#基本语法" class="headerlink" title="基本语法"></a>基本语法</h2><p>一个正则表达式通常被称为一个模式（pattern），为用来描述或者匹配一系列符合某个句法规则的字符串。</p>
<h3 id="选择"><a href="#选择" class="headerlink" title="选择"></a>选择</h3><p><code>|</code>表示分割，比如： <code>boy | gril</code>可以匹配“boy”或者“girl”</p>
<h3 id="数量限定"><a href="#数量限定" class="headerlink" title="数量限定"></a>数量限定</h3><p>数量限定出了上面讲过的<code>*</code>，还有<code>+</code>和<code>?</code>,如果在一个模式中不加数量限定符则表示出现一次且仅出现一次：</p>
<ul>
<li><code>+</code>表示前面的字符必须出现至少一次（一次或多次），例如，”goo+gle”可以匹配‘goooogle’,’gooooogle’等；</li>
<li><code>?</code>表示前面的字符最多出现一次（零次或一次），例如，“colou?r”可以匹配‘colour’和‘color’；</li>
<li><code>*</code>表示前面的字符可以不出现，也出现一次或者多次，例如，‘0*42’可以匹配42，042，0042，00042等等。</li>
</ul>
<h3 id="范围和优先级"><a href="#范围和优先级" class="headerlink" title="范围和优先级"></a>范围和优先级</h3><p><code>()</code>圆括号可以用来定义模式字符串的范围和优先级，可以简单的理解位是否将括号内的模式串作为一个整体。例如，”gr(a|r)y”等价于gray|grey；”(grand)?father”匹配father和grandfather。</p>
<h3 id="语法部分"><a href="#语法部分" class="headerlink" title="语法部分"></a>语法部分</h3><p>正则表达式有多种不同的风格，下面举例一下常用的作为PCRE子集的适合于<code>perl</code>和<code>python</code>编程语言及<code>grep</code>或<code>egrep</code>的正则表达式匹配规则。</p>
<blockquote>
<p>PCRE（Perl Compatible Regular Expressions中文含义：perl语言兼容正则表达式）是一个用 C 语言编写的正则表达式函数库，由菲利普.海泽(Philip Hazel)编写。PCRE是一个轻量级的函数库，比Boost 之类的正则表达式库小得多。PCRE 十分易用，同时功能也很强大，性能超过了 POSIX 正则表达式库和一些经典的正则表达式库。</p>
</blockquote>
<table>
<thead>
<tr>
<th>字符</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>\</td>
<td>建一个字符标记为一个特殊字符，或一个原义字符，比如，”n”匹配字符“n”, “/n”匹配一个换行符，序列”\“匹配”\”而“(”匹配”(“。</td>
</tr>
<tr>
<td>^</td>
<td>匹配输入字符串的开始位置</td>
</tr>
<tr>
<td>$</td>
<td>匹配输入字符串的结束位置</td>
</tr>
<tr>
<td>{n}</td>
<td>n是一个非负整数，匹配确定的n次，例如：”o{2}”不能匹配“Bob”种的“o”,但是能匹配“book”种的两个”o”</td>
</tr>
<tr>
<td>{n,}</td>
<td>n是一个非负整数，至少匹配n次，例如：“o{2,}“不能匹配‘bob’，但可以匹配”foooood“种的所有‘o’, <code>&quot;o{1,}&quot;等价于”o+“,&quot;o{0,}&quot;等价于”o*“</code></td>
</tr>
<tr>
<td>{n,m }</td>
<td>m和n均为非负整数，其中n&lt;=m。最少匹配n次且最多匹配m次，比如“o{1，3}”将匹配“fooooodv”种的前三个o</td>
</tr>
<tr>
<td>*</td>
<td>匹配前面的子表达式零次或多次</td>
</tr>
<tr>
<td>+</td>
<td>匹配前面的子表达式一次或多次</td>
</tr>
<tr>
<td>?</td>
<td>匹配前面的子表达式零次或一次</td>
</tr>
<tr>
<td>?</td>
<td>当该字符紧跟在任何一个其他限制符（*,+,?，{n}，{n,}，{n,m}）后面时，匹配模式是非贪婪的。非贪婪模式尽可能少的匹配所搜索的字符串，而默认的贪婪模式则尽可能多的匹配所搜索的字符串。例如，对于字符串“oooo”，“o+?”将匹配单个“o”，而“o+”将匹配所有“o”。</td>
</tr>
<tr>
<td>.</td>
<td>匹配除了”\n“之外的任何单个字符，要匹配包括“\n”在内的任何字符，请使用像“(.｜\n)”的模式。</td>
</tr>
<tr>
<td>（pattern）</td>
<td>匹配pattern并获取这一匹配的子字符串。该子字符串用户向后引用。要匹配圆括号字符，请使用“(”或“)”。</td>
</tr>
<tr>
<td>x竖线y</td>
<td>匹配x或y。 例如”z竖线food“能匹配”z“或”food”.”(z竖线f)oood”则匹配”zood“或”food“。</td>
</tr>
<tr>
<td>[xyz]</td>
<td>字符集合（character class）。匹配所包含的任意一个字符。例如，”[abc]“可以匹配”plain“中的”a”。其中特殊字符仅有反斜线\保持特殊含义，用于转义字符。其它特殊字符如星号、加号、各种括号等均作为普通字符。脱字符^如果出现在首位则表示负值字符集合；如果出现在字符串中间就仅作为普通字符。连字符 - 如果出现在字符串中间表示字符范围描述；如果如果出现在首位则仅作为普通字符。</td>
</tr>
<tr>
<td>[^xyz]</td>
<td>排除型（negate）字符集合。匹配未列出的任意字符。例如，“[^abc]”可以匹配“plain”中的“plin”。</td>
</tr>
<tr>
<td>[a-z]</td>
<td>字符范围。匹配指定范围内的任意字符。例如，“[a-z]”可以匹配“a”到“z”范围内的任意小写字母字符。</td>
</tr>
<tr>
<td>[a-z]</td>
<td>字符范围。匹配指定范围内的任意字符。例如，“[a-z]”可以匹配“a”到“z”范围内的任意小写字母字符。</td>
</tr>
</tbody>
</table>
<p><strong>注意</strong>：由于markdown的语法问题，表格中的竖线无法显示，会被编译成表格的一列，所以在表格中使用竖线（’|‘）的地方，写成了中文的“竖线”</p>
<h3 id="优先级"><a href="#优先级" class="headerlink" title="优先级"></a>优先级</h3><p>优先级为从上到下从左到右，依次降低：</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>\</td>
<td>转义符</td>
</tr>
<tr>
<td>(), (?:), (?=), []</td>
<td>括号和中括号</td>
</tr>
<tr>
<td>*、+、?、{n}、{n,}、{n,m}</td>
<td>限定符</td>
</tr>
<tr>
<td>^、$、\任何元字符</td>
<td>定位点和序列</td>
</tr>
<tr>
<td><code>｜</code></td>
<td>选择</td>
</tr>
</tbody>
</table>
<h2 id="grep模式匹配命令"><a href="#grep模式匹配命令" class="headerlink" title="grep模式匹配命令"></a>grep模式匹配命令</h2><h3 id="基本操作"><a href="#基本操作" class="headerlink" title="基本操作"></a>基本操作</h3><p><code>grep</code>命令用户打印输出文本中匹配的模式串，它使用正则表达式作为模式匹配的条件。<code>grep</code>支持三种正则表达式引擎，分别用三个参数指定：</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>-E</td>
<td>POSIX扩展正则表达式，ERE</td>
</tr>
<tr>
<td>-G</td>
<td>POSIX基本正则表达式，BRE</td>
</tr>
<tr>
<td>-P</td>
<td>Perl正则表达式，PCRE</td>
</tr>
</tbody>
</table>
<p>在通过<code>grep</code>命令使用正则表达式之前，先介绍一下它的常用参数：</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>-b</td>
<td>将二进制文件作为文本来进行匹配</td>
</tr>
<tr>
<td>-c</td>
<td>统计以模式匹配的数目</td>
</tr>
<tr>
<td>-i</td>
<td>忽略大小写</td>
</tr>
<tr>
<td>-n</td>
<td>显示匹配文本所在行的行号</td>
</tr>
<tr>
<td>-v</td>
<td>反选，输出不匹配行的内容</td>
</tr>
<tr>
<td>-r</td>
<td>递归匹配查找</td>
</tr>
<tr>
<td>-A n</td>
<td>n为正整数，表示after的意思，除了列出匹配行之外，还列出后面的n行</td>
</tr>
<tr>
<td>-B n</td>
<td>n为正整数，表示before的意思，除了列出匹配行之外，还列出前面的n行</td>
</tr>
<tr>
<td>–color=auto</td>
<td>将输出中的匹配项设置为自动颜色显示</td>
</tr>
</tbody>
</table>
<p><img src="https://i.imgur.com/lxmDrMs.png" alt=""></p>
<h3 id="使用正则表达式"><a href="#使用正则表达式" class="headerlink" title="使用正则表达式"></a>使用正则表达式</h3><h4 id="使用基本正则表达式：BRE"><a href="#使用基本正则表达式：BRE" class="headerlink" title="使用基本正则表达式：BRE"></a>使用基本正则表达式：BRE</h4><ul>
<li>位置</li>
</ul>
<p>查找<code>/etc/group</code>文件中以”shiyanlou“为开头的行</p>
<pre><code>grep &apos;shiyanlou&apos; /etc/group
grep &apos;^shiyanlou&apos; /etc/group
</code></pre><p><img src="https://i.imgur.com/0yauqRa.png" alt=""></p>
<ul>
<li>数量</li>
</ul>
<pre><code>#匹配以‘z’开头以‘o’结尾的所有字符串
echo &apos;zero\nzo\nzoo&apos; |  grep &apos;z.*o&apos;
#匹配以‘z’开头以‘o’结尾，中间包含一个任意字符的字符串
echo &apos;zero\nzo\nzoo&apos; | grep &apos;z.o&apos;
#匹配以‘z’开头，以任意多个‘o’结尾的字符串
echo &apos;zero\nzo\nzoo&apos; | grep &apos;zo*&apos;
</code></pre><p><img src="https://i.imgur.com/AFrutHC.png" alt=""></p>
<ul>
<li>选择</li>
</ul>
<pre><code>#grep默认区分大小写，这里将匹配所有的小写字母
echo &apos;1234\nabcd&apos; | greap &apos;[a-z]&apos;
#将匹配所有的数字
echo &apos;1234\nabcd&apos; | greap &apos;[0-9]&apos;
#匹配所有数字
echo &apos;1234\nabcd&apos; | greap &apos;[[:digit]]&apos;
#匹配所有小写字母
echo &apos;1234\nabcd&apos; | greap &apos;[[:lower:]]&apos;
#匹配所有大写字母
echo &apos;1234\nabcd\nABCD&apos; | greap &apos;[[:upper:]]&apos;
#匹配所有的数字和字母，包括：0-9，a-z,A-Z
echo &apos;1234\nabcd\nABCD&apos; | greap &apos;[[:alnum:]]&apos;
#匹配所有的字母
echo &apos;1234\nabcd\nABCD&apos; | greap &apos;[[:alpha:]]&apos;
</code></pre><p><img src="https://i.imgur.com/XPbf0jn.png" alt=""></p>
<p>下面包含完整的特殊符号及说明：</p>
<table>
<thead>
<tr>
<th>特殊符号</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>[:alnum:]</td>
<td>代表英文大小写字母及数字，亦即 0-9, A-Z, a-z</td>
</tr>
<tr>
<td>[:alpha:]</td>
<td>代表任何英文大小写字母，亦即 A-Z, a-z</td>
</tr>
<tr>
<td>[:blank:]</td>
<td>代表空白键与 [Tab] 按键两者</td>
</tr>
<tr>
<td>[:cntrl:]</td>
<td>代表键盘上面的控制按键，亦即包括 CR, LF, Tab, Del.. 等等</td>
</tr>
<tr>
<td>[:digit:]</td>
<td>代表数字而已，亦即 0-9</td>
</tr>
<tr>
<td>[:graph:]</td>
<td>除了空白字节 (空白键与 [Tab] 按键) 外的其他所有按键</td>
</tr>
<tr>
<td>[:lower:]</td>
<td>代表小写字母，亦即 a-z</td>
</tr>
<tr>
<td>[:print:]</td>
<td>代表任何可以被列印出来的字符</td>
</tr>
<tr>
<td>[:punct:]</td>
<td>代表标点符号 (punctuation symbol)，亦即：” ‘ ? ! ; : # $…</td>
</tr>
<tr>
<td>[:upper:]</td>
<td>代表大写字母，亦即 A-Z</td>
</tr>
<tr>
<td>[:space:]</td>
<td>任何会产生空白的字符，包括空白键, [Tab], CR 等等</td>
</tr>
<tr>
<td>[:xdigit:]</td>
<td>代表 16 进位的数字类型，因此包括： 0-9, A-F, a-f 的数字与字节</td>
</tr>
</tbody>
</table>
<pre><code># 排除字符
echo &apos;geek\ngood&apos; | grep &apos;[^o]&apos;
</code></pre><p><img src="https://i.imgur.com/i3jDsyH.png" alt=""></p>
<h3 id="使用扩展正则表达式"><a href="#使用扩展正则表达式" class="headerlink" title="使用扩展正则表达式"></a>使用扩展正则表达式</h3><p>要通过<code>grep</code>使用扩展正则表达式需要加上<code>-E</code>参数，或使用<code>egrep</code>。</p>
<ul>
<li>数量</li>
</ul>
<pre><code>#只匹配”zo“
echo &apos;zero\nzo\nzoo&apos; | grep -E &apos;zo{1}&apos;
#匹配以&apos;zo&apos;开头的所有单词
echo &apos;zero\nzo\nzoo&apos; | grep -E &apos;zo{1,}&apos;
</code></pre><p>注意：推荐掌握{n,m}即可，+,?,*，这几个不太直观，且容易弄混淆。</p>
<p><img src="https://i.imgur.com/oqIBw5Z.png" alt=""></p>
<ul>
<li>选择</li>
</ul>
<pre><code># 匹配&quot;www.shiyanlou.com&quot;和&quot;www.google.com&quot;
$ echo &apos;www.shiyanlou.com\nwww.baidu.com\nwww.google.com&apos; | grep -E &apos;www\.(shiyanlou|google)\.com&apos;
# 或者匹配不包含&quot;baidu&quot;的内容
$ echo &apos;www.shiyanlou.com\nwww.baidu.com\nwww.google.com&apos; | grep -Ev &apos;www\.baidu\.com&apos;
</code></pre><p><img src="https://i.imgur.com/rsEeFmm.png" alt=""></p>
<h2 id="sed流编辑器"><a href="#sed流编辑器" class="headerlink" title="sed流编辑器"></a>sed流编辑器</h2><p><code>sed</code>工具在 man 手册里面的全名为”sed - stream editor for filtering and transforming text “，意即，用于过滤和转换文本的流编辑器。</p>
<p>在 Linux/UNIX 的世界里敢称为编辑器的工具，大都非等闲之辈，比如前面的”vi/vim(编辑器之神)”,”emacs(神的编辑器)”,”gedit”这些个编辑器。sed与上述的最大不同之处在于它是一个非交互式的编辑器。</p>
<h3 id="sed常用参数介绍"><a href="#sed常用参数介绍" class="headerlink" title="sed常用参数介绍"></a>sed常用参数介绍</h3><p>sed命令基本格式</p>
<pre><code>sed [参数] [执行命令] [输入文件] ...
#形如
sed -i &apos;s/ad/happy&apos; test #表示将test文件中的&quot;sad&quot;替换成happy
</code></pre><table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>-n</td>
<td>安静模式，只打印受影响的行，默认打印输入数据的全部内容</td>
</tr>
<tr>
<td>-e</td>
<td>用于在脚本中添加多个执行命令一次执行，在命令行中多个命令通过需要加该参数</td>
</tr>
<tr>
<td>-f filename</td>
<td>指定执行filename文件中的命令</td>
</tr>
<tr>
<td>-r</td>
<td>使用扩展正则表达式，默认为标准正则表达式</td>
</tr>
<tr>
<td>-i</td>
<td>直接修改输入文件内容，而不是打印到输出标准设备</td>
</tr>
</tbody>
</table>
<h3 id="sed编译器的执行命令"><a href="#sed编译器的执行命令" class="headerlink" title="sed编译器的执行命令"></a>sed编译器的执行命令</h3><p>sed 执行格式：</p>
<pre><code>[n1][,n2]command
[n1][~step]command
# 其中一些命令可以在后面加上作用范围，形如：
$ sed -i &apos;s/sad/happy/g&apos; test # g表示全局范围
$ sed -i &apos;s/sad/happy/4&apos; test # 4表示指定行中的第四个匹配字符串
</code></pre><p>其中n1,n2表示输入内容的行号，它们之间为,逗号则表示从n1到n2行，如果为～波浪号则表示从n1开始以step为步进的所有行；command为执行动作，下面为一些常用动作指令：</p>
<table>
<thead>
<tr>
<th>命令</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>s</td>
<td>行内替换</td>
</tr>
<tr>
<td>c</td>
<td>整行替换</td>
</tr>
<tr>
<td>a</td>
<td>插入到指定行的后面</td>
</tr>
<tr>
<td>i</td>
<td>插入到指定行的前面</td>
</tr>
<tr>
<td>p</td>
<td>打印指定行，通常与-n参数配合使用</td>
</tr>
<tr>
<td>d</td>
<td>删除指定行</td>
</tr>
</tbody>
</table>
<h3 id="sed操作举例"><a href="#sed操作举例" class="headerlink" title="sed操作举例"></a>sed操作举例</h3><h4 id="打印指定行"><a href="#打印指定行" class="headerlink" title="打印指定行"></a>打印指定行</h4><pre><code>#打印2-5行
nl passwd | sed -n &apos;2,5p&apos;
#打印奇数行
nl passwd | sed -n &apos;1~2p&apos;
</code></pre><p><img src="https://i.imgur.com/wp4CVrc.png" alt=""></p>
<p>注意：nl 可以将输出的文件内容自动的加上行号</p>
<h4 id="行内替换"><a href="#行内替换" class="headerlink" title="行内替换"></a>行内替换</h4><pre><code>#文本中”shiyanlou“全局替换成’hehe‘，并纸打印替换的那一行，注意这里不能省略最后的”p“命令
sed -n &apos;s/shiyanlou/hehe/gp&apos; passwd
</code></pre><p>注意： 行内替换可以结合正则表达式使用。</p>
<p><img src="https://i.imgur.com/BQNSaoo.png" alt=""></p>
<h4 id="行间替换"><a href="#行间替换" class="headerlink" title="行间替换"></a>行间替换</h4><pre><code>nl passwd | grep &apos;shiyanlou&apos;
#删除第21行
sed -n &apos;21c\www.shiyanlou.com&apos; passwd
（这里我们只把要删的行打印出来了，并没有真正的删除，如果要删除的话，请使用-i参数）
</code></pre><p><img src="https://i.imgur.com/sBRTNbn.png" alt=""></p>
<h2 id="awk文本处理语言"><a href="#awk文本处理语言" class="headerlink" title="awk文本处理语言"></a>awk文本处理语言</h2><p>AWK是一种优良的文本处理工具，Linux及Unix环境中现有的功能最强大的数据处理引擎之一.其名称得自于它的创始人Alfred Aho（阿尔佛雷德·艾侯）、Peter Jay Weinberger（彼得·温伯格）和Brian Wilson Kernighan（布莱恩·柯林汉)姓氏的首个字母.AWK程序设计语言，三位创建者已将它正式定义为“样式扫描和处理语言”。它允许您创建简短的程序，这些程序读取输入文件、为数据排序、处理数据、对输入执行计算以及生成报表，还有无数其他的功能。最简单地说，AWK是一种用于处理文本的编程语言工具。</p>
<p>在大多数linux发行版上面，实际我们使用的是gawk（GNU awk，awk的GNU版本）。</p>
<p>nawk： 在 20 世纪 80 年代中期，对 awk语言进行了更新，并不同程度地使用一种称为 nawk(new awk) 的增强版本对其进行了替换。许多系统中仍然存在着旧的awk 解释器，但通常将其安装为 oawk (old awk) 命令，而 nawk 解释器则安装为主要的 awk 命令，也可以使用 nawk 命令。Dr. Kernighan 仍然在对 nawk 进行维护，与 gawk 一样，它也是开放源代码的，并且可以免费获得; gawk： 是 GNU Project 的awk解释器的开放源代码实现。尽管早期的 GAWK 发行版是旧的 AWK 的替代程序，但不断地对其进行了更新，以包含 NAWK 的特性; mawk 也是awk编程语言的一种解释器，mawk遵循 POSIX 1003.2 （草案 11.3）定义的 AWK 语言，包含了一些没有在AWK 手册中提到的特色，同时 mawk 提供一小部分扩展,另外据说mawk是实现最快的awk。</p>
<h3 id="awk的基础概念"><a href="#awk的基础概念" class="headerlink" title="awk的基础概念"></a>awk的基础概念</h3><p>awk所有的操作都是基于pattern（模式）—action(动作)对来完成的，如下面的形式：</p>
<pre><code>pattern {action}
</code></pre><p>它将所有的动作操作用一对{}花括号包围起来。其中pattern通常是表示用于匹配输入的文本的“关系式”或“正则表达式”，action则是表示匹配后将执行的动作。在一个完整awk操作中，这两者可以只有其中一个，如果没有pattern则默认匹配输入的全部文本，如果没有action则默认为打印匹配内容到屏幕。</p>
<p>awk处理文本的方式，是将文本分割成一些“字段”，然后再对这些字段进行处理，默认情况下，awk以空格作为一个字段的分割符，不过这不是固定的，你可以任意指定分隔符。</p>
<h4 id="awk命令基本格式"><a href="#awk命令基本格式" class="headerlink" title="awk命令基本格式"></a>awk命令基本格式</h4><pre><code>awk [-F fs] [-v var=value] [-f prog-file] | &apos;program text&apos;] [file...]
</code></pre><p>其中<code>-F</code>参数用于预先指定前面提高的字段分隔符（还有其他指定字段的方式），<code>-v</code>用户预先为<code>awk</code>程序指定变量，<code>-f</code>参数用户指定<code>awk</code>命令要执行的程序文件，或者在不加’-f’参数的情况下直接间程序语句放在这里。最后为<code>awk</code>需要处理的文本输入，且可以同时输入多个文本文件。</p>
<h3 id="awk操作体验"><a href="#awk操作体验" class="headerlink" title="awk操作体验"></a>awk操作体验</h3><pre><code>vim test
#输入文本
cat test
</code></pre><h4 id="使用swk将文本打印到终端"><a href="#使用swk将文本打印到终端" class="headerlink" title="使用swk将文本打印到终端"></a>使用swk将文本打印到终端</h4><pre><code>awk &apos;{
print
}&apos; test
#或者写成一行
awk &apos;{print}&apos; test
</code></pre><p>说明:在这个操作中我是省略了pattern，所以awk会默认匹配输入文本的全部内容，然后在”{}”花括号中执行动作，即print打印所有匹配项，这里是全部文本内容</p>
<p><img src="https://i.imgur.com/3DVhZlj.png" alt=""></p>
<h4 id="将test的第一行中的每个字段单独显示为一行"><a href="#将test的第一行中的每个字段单独显示为一行" class="headerlink" title="将test的第一行中的每个字段单独显示为一行"></a>将test的第一行中的每个字段单独显示为一行</h4><pre><code>$ awk &apos;{
&gt; if(NR==1){
&gt; print $1 &quot;\n&quot; $2 &quot;\n&quot; $3
&gt; } else {
&gt; print}
&gt; }&apos; test

# 或者
$ awk &apos;{
&gt; if(NR==1){
&gt; OFS=&quot;\n&quot;
&gt; print $1, $2, $3
&gt; } else {
&gt; print}
&gt; }&apos; test
</code></pre><p><img src="https://i.imgur.com/ZwgDOrO.png" alt=""></p>
<p>说明:你首先应该注意的是，这里我使用了awk语言的分支选择语句if,它的使用和很多高级语言如C/C++语言基本一致，如果你有这些语言的基础，这里将很好理解。另一个你需要注意的是<code>NR</code>与<code>OFS</code>，这两个是awk内建的变量，<code>NR</code>表示当前读入的记录数，你可以简单的理解为当前处理的行数，<code>OFS</code>表示输出时的字段分隔符，默认为” “空格，如上图所见，我们将字段分隔符设置为<code>\n</code>换行符，所以第一行原本以空格为字段分隔的内容就分别输出到单独一行了。然后是<code>$N</code>其中N为相应的字段号，这也是awk的内建变量，它表示引用相应的字段，因为我们这里第一行只有三个字段，所以只引用到了<code>$3</code>。除此之外另一个这里没有出现的<code>$0</code>，它表示引用当前记录（当前行）的全部内容。</p>
<h4 id="将test的第行以点为分段的字段换成以空格为风格"><a href="#将test的第行以点为分段的字段换成以空格为风格" class="headerlink" title="将test的第行以点为分段的字段换成以空格为风格"></a>将test的第行以点为分段的字段换成以空格为风格</h4><pre><code>$ awk -F&apos;.&apos; &apos;{
&gt; if(NR==2){
&gt; print $1 &quot;\t&quot; $2 &quot;\t&quot; $3
&gt; }}&apos; test

# 或者
$ awk &apos;
&gt; BEGIN{
&gt; FS=&quot;.&quot;
&gt; OFS=&quot;\t&quot;  # 如果写为一行，两个动作语句之间应该以&quot;;&quot;号分开  
&gt; }{
&gt; if(NR==2){
&gt; print $1, $2, $3
&gt; }}&apos; test
</code></pre><p><img src="https://i.imgur.com/crQqo4i.png" alt=""> <img src="https://i.imgur.com/sdHzSiw.png" alt=""></p>
<p>说明：这里的<code>-F</code>参数，前面已经介绍过，它是用来预先指定待处理记录的字段分隔符。我们需要注意的是除了指定<code>OFS</code>我们还可以在<code>print</code> 语句中直接打印特殊符号如这里的<code>\t</code>，<code>print</code>打印的非变量内容都需要用””一对引号包围起来。上面另一个版本，展示了实现预先指定变量分隔符的另一种方式，即使用<code>BEGIN</code>，就这个表达式指示了，其后的动作将在所有动作之前执行，这里是<code>FS</code>赋值了新的”.”点号代替默认的” “空格</p>
<h3 id="awk常用的内置变量"><a href="#awk常用的内置变量" class="headerlink" title="awk常用的内置变量"></a>awk常用的内置变量</h3><table>
<thead>
<tr>
<th>变量名</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>FILENAME</td>
<td>当前输入文件名，若有多个文件，则只表示第一个。如果输入是来自标准输入，则为空字符串</td>
</tr>
<tr>
<td>$0</td>
<td>当前记录的内容</td>
</tr>
<tr>
<td>$N</td>
<td>N表示字段号，最大值为NF变量的值</td>
</tr>
<tr>
<td>FS</td>
<td>字段分隔符，由正则表达式表示，默认为” “空格</td>
</tr>
<tr>
<td>RS</td>
<td>输入记录分隔符，默认为”\n”，即一行为一个记录</td>
</tr>
<tr>
<td>NF</td>
<td>当前记录字段数</td>
</tr>
<tr>
<td>NR</td>
<td>已经读入的记录数</td>
</tr>
<tr>
<td>FNR</td>
<td>当前输入文件的记录数，请注意它与NR的区别</td>
</tr>
<tr>
<td>OFS</td>
<td>输出字段分隔符，默认为” “空格</td>
</tr>
<tr>
<td>ORS</td>
<td>输出记录分隔符，默认为”\n”</td>
</tr>
</tbody>
</table>

      
    </div>
    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/images/wechat-qcode.jpg" alt="zxp wechat" style="width: 200px; max-width: 100%;"/>
    <div>欢迎关注微信公众号！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/WeChatpay.jpg" alt="zxp 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/Alipay.jpg" alt="zxp 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zxp
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zxpgo.github.io/2018/09/01/正则表达式基础/" title="正则表达式基础">https://zxpgo.github.io/2018/09/01/正则表达式基础/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tag/Linux/" rel="tag"># Linux</a>
          
            <a href="/tag/正则表达式/" rel="tag"># 正则表达式</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/09/01/Centos设置默认进入图形界面和命令行界面/" rel="next" title="Centos7设置默认进入图形界面和命令行界面">
                <i class="fa fa-chevron-left"></i> Centos7设置默认进入图形界面和命令行界面
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/09/01/Linux下软件安装/" rel="prev" title="Linux下软件安装">
                Linux下软件安装 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODgxNC8xNTM0Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.gif"
                alt="zxp" />
            
              <p class="site-author-name" itemprop="name">zxp</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">176</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">48</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_25774883" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zxpgo/zxpgo" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-globe"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.linkedin.com/feed/" target="_blank" title="LinkedIn">
                      
                        <i class="fa fa-fw fa-globe"></i>LinkedIn</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="1165772354@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://theme-next.iissnan.com" title="Next主题" target="_blank">Next主题</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.rexking6.top" title="青爷博客" target="_blank">青爷博客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://me.csdn.net/download/qq_25774883" title="CSDN下载" target="_blank">CSDN下载</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.livere.com/" title="来必力" target="_blank">来必力</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://tongji.baidu.com/web/welcome/login" title="百度统计" target="_blank">百度统计</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leancloud.cn/" title="LeanCloud" target="_blank">LeanCloud</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ibruce.info/2015/04/04/busuanzi/" title="不蒜子" target="_blank">不蒜子</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leetcode-cn.com/" title="LeetCode" target="_blank">LeetCode</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#概念"><span class="nav-number">1.</span> <span class="nav-text">概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基本语法"><span class="nav-number">2.</span> <span class="nav-text">基本语法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#选择"><span class="nav-number">2.1.</span> <span class="nav-text">选择</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数量限定"><span class="nav-number">2.2.</span> <span class="nav-text">数量限定</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#范围和优先级"><span class="nav-number">2.3.</span> <span class="nav-text">范围和优先级</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#语法部分"><span class="nav-number">2.4.</span> <span class="nav-text">语法部分</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优先级"><span class="nav-number">2.5.</span> <span class="nav-text">优先级</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#grep模式匹配命令"><span class="nav-number">3.</span> <span class="nav-text">grep模式匹配命令</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#基本操作"><span class="nav-number">3.1.</span> <span class="nav-text">基本操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用正则表达式"><span class="nav-number">3.2.</span> <span class="nav-text">使用正则表达式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#使用基本正则表达式：BRE"><span class="nav-number">3.2.1.</span> <span class="nav-text">使用基本正则表达式：BRE</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用扩展正则表达式"><span class="nav-number">3.3.</span> <span class="nav-text">使用扩展正则表达式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#sed流编辑器"><span class="nav-number">4.</span> <span class="nav-text">sed流编辑器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#sed常用参数介绍"><span class="nav-number">4.1.</span> <span class="nav-text">sed常用参数介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#sed编译器的执行命令"><span class="nav-number">4.2.</span> <span class="nav-text">sed编译器的执行命令</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#sed操作举例"><span class="nav-number">4.3.</span> <span class="nav-text">sed操作举例</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#打印指定行"><span class="nav-number">4.3.1.</span> <span class="nav-text">打印指定行</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#行内替换"><span class="nav-number">4.3.2.</span> <span class="nav-text">行内替换</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#行间替换"><span class="nav-number">4.3.3.</span> <span class="nav-text">行间替换</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#awk文本处理语言"><span class="nav-number">5.</span> <span class="nav-text">awk文本处理语言</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#awk的基础概念"><span class="nav-number">5.1.</span> <span class="nav-text">awk的基础概念</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#awk命令基本格式"><span class="nav-number">5.1.1.</span> <span class="nav-text">awk命令基本格式</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#awk操作体验"><span class="nav-number">5.2.</span> <span class="nav-text">awk操作体验</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#使用swk将文本打印到终端"><span class="nav-number">5.2.1.</span> <span class="nav-text">使用swk将文本打印到终端</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#将test的第一行中的每个字段单独显示为一行"><span class="nav-number">5.2.2.</span> <span class="nav-text">将test的第一行中的每个字段单独显示为一行</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#将test的第行以点为分段的字段换成以空格为风格"><span class="nav-number">5.2.3.</span> <span class="nav-text">将test的第行以点为分段的字段换成以空格为风格</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#awk常用的内置变量"><span class="nav-number">5.3.</span> <span class="nav-text">awk常用的内置变量</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div>
<script async src="https//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    访问人数 <span id="busuanzi_value_site_uv"></span>
</span>
</div>


<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; 2018-8 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-"></i> Power by 
  </span>
  <span class="author" itemprop="copyrightHolder">zxp</span>
  
  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  




  
  <div id="lv-container" data-uid="MTAyMC8zODgxNC8xNTM0Mg==">
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
	</div>
  











  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("2AyV3DKioBSdoryrFLRohzjB-gzGzoHsz", "XynedcHyJCVCrTfbD4yYnodo");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "vertical";
      
          pbOptions.position = "top";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


  
  
  	 <!-- custom analytics part create by xiamo -->
<script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
<script>AV.initialize("2AyV3DKioBSdoryrFLRohzjB-gzGzoHsz", "XynedcHyJCVCrTfbD4yYnodo");</script>
<script>
function showTime(Counter) {
	var query = new AV.Query(Counter);
	$(".leancloud_visitors").each(function() {
		var url = $(this).attr("id").trim();
		query.equalTo("url", url);
		query.find({
			success: function(results) {
				if (results.length == 0) {
					var content = $(document.getElementById(url)).text() + ' 0';
					$(document.getElementById(url)).text(content);
					return;
				}
				for (var i = 0; i < results.length; i++) {
					var object = results[i];
					var content = $(document.getElementById(url)).text() + ' ' + object.get('time');
					$(document.getElementById(url)).text(content);
				}
			}
		});

	});
}

</script>
  
</body>
</html>
